#include "BlockQueue.hpp"
#include "Task.hpp"
#include "Thread.hpp"
#include <string>
#include <vector>
#include <ctime>
#include <unistd.h>

using namespace ThreadModule;

int _num = 10;
using blockqueue_t = BlockQueue<Task>;

// void P()
// {
//     std::cout<<"bhyudiqwhn"<<std::endl;
// }


void Consumer(blockqueue_t &bq)
{
    while(true)
    {
        //拉去任务
        Task t;
        bq.Pop(&t);
       

       //处理任务
        //t();
        t.Excute();
        std::cout<<"消费者消费了一个任务:"<<t.ResultToString()<<std::endl;
    }
}

void Productor(blockqueue_t &bq)
{
    srand(time(nullptr)^pthread_self());

    int cnt=10;

    while(true)
    {
      int a=rand()%10+1;
      usleep(1232);
      int b=rand()%40+1;
      Task t(a,b);
      bq.Enqueue(t);

      std::cout<<"生产者生产了一个任务:"<<t.DebugToString()<<std::endl;      

         sleep(1);
         
        //  //放入任务
        // Task t=P;
        // bq.Enqueue(t);
        
    }
}


void StartCom(std::vector<Thread<blockqueue_t>> *vec, int num, blockqueue_t &bq,func_t<blockqueue_t> func)
{

    for(int i = 0; i < num; ++i)
    {

        std::string name = "Thread-" + std::to_string(i+1);
        vec->emplace_back(func,bq,name);
        vec->back().Start();
    }
}

void StartConsumer(std::vector<Thread<blockqueue_t>> *vec, int num, blockqueue_t &bq)
{
 
   StartCom(vec, num, bq, Consumer);
}

void StartProductor(std::vector<Thread<blockqueue_t>> *vec, int num, blockqueue_t &bq)
{

   StartCom(vec, num, bq, Productor);
}

void WaitAllThread(std::vector<Thread<blockqueue_t>> &vec)
{
    for(auto &t : vec)
    {
        t.Join();
    }
}


int main()
{
    blockqueue_t *bq = new blockqueue_t(5);
   
    std::vector<Thread<blockqueue_t>> vec;
    StartProductor(&vec, 1, *bq);
    StartConsumer(&vec, 3, *bq);

    WaitAllThread(vec);

    return 0;
}